package com.msda.service.staff.Impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.msda.mapper.CustomerMapper;
import com.msda.mapper.UserMapper;
import com.msda.pojo.dto.PageDTO;
import com.msda.pojo.dto.staff.AuditApprovalDTO;
import com.msda.pojo.entity.requirement.CustomerApproval;
import com.msda.pojo.entity.staff.Customer;
import com.msda.exception.database.DatabaseOperationException;
import com.msda.mapper.CustomerApprovalMapper;
import com.msda.pojo.entity.staff.CustomerDetail;
import com.msda.pojo.entity.staff.User;
import com.msda.pojo.vo.InquireApprovalVO;
import com.msda.service.staff.ApprovalService;
import com.msda.utils.SnowFlakeID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.msda.constant.MessageConstant.ACCOUNT_NOT_EXIST;

@Service
public class ApprovalServiceImpl implements ApprovalService {
    @Autowired
    private CustomerApprovalMapper customerApprovalMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CustomerMapper customerMapper;

    @Override
    public String customerRegister(Customer customer) {

        LambdaQueryWrapper<CustomerApproval> wrapper = new LambdaQueryWrapper<>();
        wrapper.apply("JSON_EXTRACT(customer_info, '$.account') = {0}", customer.getAccount())
                .and(w -> w.eq(CustomerApproval::getStatus, 1)
                .or()
                .eq(CustomerApproval::getStatus, 2));
//        wrapper.apply("JSON_EXTRACT(customer_info, '$.account') = {0}", customer.getAccount());
//        wrapper.eq(CustomerApproval::getStatus,1).or().eq(CustomerApproval::getStatus,2);
        List<CustomerApproval> list = customerApprovalMapper.selectList(wrapper);
        if(!list.isEmpty()){
            System.out.println(list);
            throw new DatabaseOperationException("账号已经被注册或已经提交过申请！");
        }
        customer.setId(SnowFlakeID.getSnowflakeId());
        customer.setFrozen(false);
        customer.setRole("customer");
        customer.setPassword(SaSecureUtil.md5(customer.getPassword()));
        customer.setCreatedDate(System.currentTimeMillis());
        CustomerApproval customerApproval = new CustomerApproval(SnowFlakeID.getSnowflakeId(),
                customer,2,"",false, 0L,System.currentTimeMillis());
        int i = customerApprovalMapper.insert(customerApproval);
        if( i < 1){
            throw new DatabaseOperationException("后台异常导致申请失败！");
        }
        return "申请成功！";
    }

    @Override
    public Object inquireState(String account) {
        LambdaQueryWrapper<CustomerApproval> wrapper = new LambdaQueryWrapper<>();
        wrapper.apply("JSON_EXTRACT(customer_info, '$.account') = {0}", account);
        CustomerApproval customerApproval = customerApprovalMapper.selectOne(wrapper);
        if(customerApproval == null){
            throw new DatabaseOperationException(ACCOUNT_NOT_EXIST);
        }
        int i = customerApproval.getStatus();

        if(i == 0){
            InquireApprovalVO inquireApprovalVO = new InquireApprovalVO();
            inquireApprovalVO.setStatus(0);
            inquireApprovalVO.setComments(customerApproval.getComments());
            return inquireApprovalVO;
        }
        return i;
    }

    @Override
    public Integer quashRegister(String account) {
        LambdaQueryWrapper<CustomerApproval> wrapper = new LambdaQueryWrapper<>();
        wrapper.apply("JSON_EXTRACT(customer_info, '$.account') = {0}", account);
        int i = customerApprovalMapper.delete(wrapper);
        return i;
    }

    @Override
    public Integer auditApproval(AuditApprovalDTO auditApprovalDTO) {
        CustomerApproval customerApproval = customerApprovalMapper.selectById(auditApprovalDTO.getId());
        if(customerApproval == null){
            throw new DatabaseOperationException("申请不存在！");
        }
        customerApproval.setStatus(auditApprovalDTO.getStatus());
        customerApproval.setProcessTime(System.currentTimeMillis());
        customerApproval.setFinished(true);
        if(auditApprovalDTO.getStatus() == 0){
            customerApproval.setComments(auditApprovalDTO.getComments());
        }
        if(auditApprovalDTO.getStatus() == 1){
            User customer = new User();
            BeanUtil.copyProperties(customerApproval.getCustomerInfo(),customer);

            userMapper.insert(customer);
            customerMapper.insert(CustomerDetail.builder()
                    .id(SnowFlakeID.getSnowflakeId())
                    .userId(customer.getId())
                    .phone(customerApproval.getCustomerInfo().getPhone())
                    .companyName(customerApproval.getCustomerInfo().getCompanyName())
                    .build());
        }
        int i = customerApprovalMapper.updateById(customerApproval);
        return i;
    }

    @Override
    public Long getAllApproval(int status) {

        QueryWrapper<CustomerApproval> queryWrapper =new QueryWrapper<>();
        if(status == 0 ){
            queryWrapper.eq("status",0).or().eq("status",1);
        } else if(status == 1){
            queryWrapper.eq("status",2);
        } else {
            throw new DatabaseOperationException("请求参数不是0/1！");
        }
        Long i = customerApprovalMapper.selectCount(queryWrapper);
        return i;
    }

    @Override
    public List<CustomerApproval> getPageApproval(int status,PageDTO pageDTO) {
        Page<CustomerApproval> page = new Page<>(pageDTO.getPage(),pageDTO.getSize());
        QueryWrapper<CustomerApproval> queryWrapper =new QueryWrapper<>();
        if(status == 0 ){
            queryWrapper.eq("status",0).or().eq("status",1);
        } else if(status == 1){
            queryWrapper.eq("status",2);
        } else {
            throw new DatabaseOperationException("请求参数不是0/1！");
        }
        queryWrapper.orderByDesc("created_time");
        page = customerApprovalMapper.selectPage(page,queryWrapper);
        return page.getRecords();
    }


}
